#!/usr/bin/env bash

__service_check() {
    local _service_name=$1
    local _timeout=3
    local _interval=1
    local _elapsed=0

    while [ $_elapsed -lt $_timeout ]; do
        if systemctl is-active --quiet "$_service_name"; then
            echo "服务 $_service_name 已正常运行"
            systemctl status "$_service_name"
            return 0
        fi
        sleep $_interval
        _elapsed=$((_elapsed + _interval))
    done

    echo "服务 $_service_name 未在 $_timeout 秒内正常运行"
    return 1
}

__exec_start() {
    :
    {
        # 初始化设备id
        _file="/data/kuaicdn/labels/suid"
        _suid=$(cat "$_file" 2>/dev/null)
        if [[ "$_suid" == "" ]]; then
            echo "suid 不存在"
            exit 1
        fi
    }

    {

        _label_ipmi_ip=$(cat /data/kuaicdn/labels/ipmi_ip 2>/dev/null)
        _label_ipmi_wg=$(cat /data/kuaicdn/labels/ipmi_wg 2>/dev/null)
        _label_group=$(cat /data/kuaicdn/labels/group 2>/dev/null)
        _label_bbiz=$(cat /data/kuaicdn/labels/bbiz 2>/dev/null)

        _description="ipmi_ip: $_label_ipmi_ip, group: $_label_group, bbiz: $_label_bbiz"
        _server_name="1122.s.kuaicdn.cn"
        _port="11222"
        _token="qwertyuiopasdfghjklzxcvbnm"
    }

    exec m-rtty -I "$_suid" -h "$_server_name" -p "$_port" -a -v -d "${_description:0:126}" -t "$_token" -s -x -f root

}

__main() {
    _service_name="m-rtty-1122"

    {
        # 检查是否需要安装服务
        _is_install=0
        _ipmi_print=$(ipmitool lan print 2>/dev/null)
        _is_gateway=$(echo "$_ipmi_print" | grep '^.*Gateway.*\s(10|11)\..*\.0\.(1|254)$' -Ec)
        _is_ipaddr=$(echo "$_ipmi_print" | grep '^.*Address.*\s(10|11)\..*\.1$' -Ec)
        if [[ "$_is_gateway" == "1" && "$_is_ipaddr" == "1" ]]; then
            _is_install=1

        fi

        if [[ "$_is_install" == "0" ]]; then
            echo "Not gateway or ipaddr"
            echo "无需安装服务: $_service_name"
            {
                systemctl stop $_service_name.service
                systemctl disable $_service_name.service
                rm -f /etc/systemd/system/$_service_name.service
            } >/dev/null 2>&1
            exit 1
        fi

    }

    {
        # 历史遗留问题，删除旧版本
        # 2024年09月10日17:04:12
        systemctl stop suprce-rtty.service
        systemctl stop suprce-rtty-t240621.service

        systemctl disable suprce-rtty.service
        systemctl disable suprce-rtty-t240621.service

        rm -f /etc/systemd/system/suprce-rtty.service
        rm -f /etc/systemd/system/suprce-rtty-t240621.service

    } >/dev/null 2>&1

    {
        _download_url="https://1133.s.kuaicdn.cn:11338/public/project/240710-rtty/bin/rtty"
        _file_name="rtty"
        _version="v8.1.2"
        _bin_name="m-rtty"
        # echo "_file_name: $_file_name, _bin_name: $_bin_name, _version: $_version"

        _bin_path="/data/kuaicdn/cellar/$_file_name/$_version/bin/$_file_name"
        _bin_ln="/usr/local/bin/$_bin_name"
        md5sum $_bin_ln | grep 2b072fd87015d3917424eee0ea95000c -cq || {
            systemctl stop $_service_name.service
            mkdir -p "${_bin_path%/*}"
            wget -O "$_bin_path" "$_download_url"
            chmod +x "$_bin_path"
            ln -sf "$_bin_path" $_bin_ln
        }
    }

    {
        FUNC_NAME=__exec_start
        FUNC_BASE64="$(declare -f $FUNC_NAME | sed "\$a $FUNC_NAME" | base64 -w0)"
        _md5_1=$(echo "$FUNC_BASE64" | md5sum | awk '{print $1}')
        _md5_2=$(cat /data/kuaicdn/labels/* | md5sum | awk '{print $1}')
        _md5_3="3"
        _config_md5sum=$(echo "$_md5_1 $_md5_2 $_md5_3" | md5sum | awk '{print $1}')
    }

    systemctl show $_service_name.service -p Environment | grep -q "CONFIG_MD5SUM=$_config_md5sum" || { systemctl stop $_service_name.service; }
    # systemctl stop $_service_name.service # 调试用
    systemctl is-active --quiet $_service_name.service || {
        {
            systemctl stop $_service_name.service
            systemctl disable $_service_name.service
            rm -f /etc/systemd/system/$_service_name.service
        } >/dev/null 2>&1
        cat >/etc/systemd/system/$_service_name.service <<EOF
[Unit]
After=network.target

[Service]
Environment="CONFIG_MD5SUM=$_config_md5sum"
Environment="SHELL=/bin/bash"
Environment="HOME=/root"
Environment="TERM=xterm-256color"
Environment="DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/0/bus"

ExecStart=/bin/bash -c 'bash <(base64 -d <<<"$FUNC_BASE64")'

Restart=always
RestartSec=5s

# 做一些限制, 避免写的程序不当导致资源耗尽

# 限制 CPU 使用率为 50%
CPUQuota=50%

[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        systemctl enable $_service_name.service
        systemctl start $_service_name.service

        sleep 1
        __service_check $_service_name.service
    }

    {
        # 检查服务运行时间，超过 4 小时则重启
        # 外部变量 _service_name
        # 获取进程 ID 并检查运行时间
        _pid=$(systemctl show -p MainPID $_service_name.service | awk -F= '{print $NF}')
        _max_runtime=$((4 * 60 * 60)) # 4 小时的秒数
        _current_runtime=$(ps -p "$_pid" -o etimes= | awk '{print $NF}')
        echo "服务 $_service_name 已运行 $_current_runtime 秒"
        if [[ $_current_runtime -ge $_max_runtime ]]; then
            echo "服务 $_service_name 已运行超过 4 小时，重启中..."
            systemctl restart $_service_name.service
        fi
    }

}

__main

__help() {
    cat >/dev/null <<-'EOF'

curl -fsSL https://1142.s.kuaicdn.cn:11428/os-monitor-t2407300/master/raw/branch/main/systemd/m-rtty-1122.sh | bash

EOF
}
